'use client';

import React, { useMemo } from 'react';
import EChartBase from './EChartBase';
import { EChartsOption } from 'echarts';

export interface TreeNode {
  name: string;
  value?: number;
  children?: TreeNode[];
  itemStyle?: {
    color?: string;
    borderColor?: string;
  };
  lineStyle?: {
    color?: string;
    width?: number;
    type?: 'solid' | 'dashed' | 'dotted';
  };
}

interface TreeChartProps {
  title?: string;
  data: TreeNode;
  height?: string | number;
  width?: string | number;
  orient?: 'LR' | 'RL' | 'TB' | 'BT'; // 树的布局方向
  expandAndCollapse?: boolean; // 是否支持展开和收起
  initialTreeDepth?: number; // 初始展开的层级
  colorPalette?: string[]; // 自定义颜色
  className?: string;
  loading?: boolean;
  errorMessage?: string;
  emptyDataMessage?: string;
}

/**
 * 树状图组件
 */
const TreeChart: React.FC<TreeChartProps> = ({
  title,
  data,
  height = '600px',
  width = '100%',
  orient = 'TB', // 默认从上到下
  expandAndCollapse = true,
  initialTreeDepth = 2,
  colorPalette,
  className,
  loading = false,
  errorMessage,
  emptyDataMessage,
}) => {
  const chartOption = useMemo<EChartsOption>(() => {
    return {
      title: title ? {
        text: title,
        left: 'center'
      } : undefined,
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}'
      },
      color: colorPalette,
      series: [
        {
          type: 'tree',
          data: [data],
          top: '10%',
          left: '8%',
          bottom: '8%',
          right: '8%',
          symbolSize: 12,
          orient: orient,
          expandAndCollapse: expandAndCollapse,
          initialTreeDepth: initialTreeDepth,
          label: {
            position: orient === 'LR' ? 'right' : 'left',
            verticalAlign: 'middle',
            align: orient === 'LR' ? 'left' : 'right',
            fontSize: 14
          },
          leaves: {
            label: {
              position: orient === 'LR' ? 'right' : 'left',
              verticalAlign: 'middle',
              align: orient === 'LR' ? 'left' : 'right'
            }
          },
          emphasis: {
            focus: 'descendant'
          },
          animationDuration: 550,
          animationDurationUpdate: 750
        }
      ]
    };
  }, [title, data, orient, expandAndCollapse, initialTreeDepth, colorPalette]);

  // 检查数据是否有效
  const hasValidData = data && data.name && (
    data.children && Array.isArray(data.children) && data.children.length > 0
  );

  return (
    <EChartBase
      option={chartOption}
      style={{ height, width }}
      className={className}
      loading={loading}
      errorMessage={errorMessage}
      emptyDataMessage={emptyDataMessage || '暂无树状图数据'}
      shouldRenderChart={() => hasValidData}
    />
  );
};

export default TreeChart; 